package com.wzs.easytobuy.service.impl;

import com.wzs.easytobuy.exception.NotEnoughException;
import com.wzs.easytobuy.mapper.*;
import com.wzs.easytobuy.model.*;
import com.wzs.easytobuy.service.ICarService;
import com.wzs.easytobuy.utils.DateTimeUtil;
import com.wzs.easytobuy.utils.UUIDUtil;
import com.wzs.easytobuy.vo.PaginationVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author miaomiao
 * @version 1.0.0
 * @Description 处理购物车相关业务的接口实现类
 * @createTime 2021-06-29- 10:50:00
 */
@Service
public class ICarServiceImpl implements ICarService {

    @Resource
    private ShoppingCarMapper shoppingCarMapper;
    @Resource
    private FormatMapper formatMapper;
    @Resource
    private ProductMapper productMapper;
    @Resource
    private AddressMapper addressMapper;
    @Resource
    private OrderMapper orderMapper;


    @Override
    public List<ShoppingCar> selectByUid(String userId) {
        return shoppingCarMapper.selectByUid(userId);
    }

    @Transactional
    @Override
    public boolean addProduct(String productId, String userId, String price, String imageUrl, String sales, int number) {
        boolean flag = true;
        boolean flag1 = false;
        int count;
        int num = 0;

        String id = UUIDUtil.getUUID();
        Format format = formatMapper.selectByIdAndPs(productId, Integer.parseInt(price), Integer.parseInt(sales));
        Product product = productMapper.selectByPrimaryKey(productId);
        String formatId = format.getId();
        String productName = product.getProductName();

        ShoppingCar s = new ShoppingCar();
        s.setUserId(userId);
        s.setNumber(number);
        s.setPrice(Integer.parseInt(price));
        s.setImageUrl(imageUrl);
        s.setId(id);
        s.setFormatId(formatId);
        s.setProductName(productName);

        ShoppingCar shop = shoppingCarMapper.selectByFidAndUid(formatId, userId);
        int store = formatMapper.getStoreById(formatId);

        //首先判断库存是否足够
        if (store > number) {
            //库存足够
            //再判断该商品是否已经存在购物车中,
            if (shop != null) {
                flag1 = true;
                num = shop.getNumber();
            }
        } else {
            //说明库存不够
            throw new NotEnoughException("该商品库存不足");
        }

        if (flag1) {
            //若存在则number加1,再更新购物车中的信息
            num += number;
            count = shoppingCarMapper.updateNumById(num, shop.getId());
        } else {
            count = shoppingCarMapper.addProduct(s);
        }
        if (count != 1) {
            flag = false;
        }

        return flag;
    }

    @Override
    public boolean addProduct2(String productId, String userId, String price, String imageUrl, int number, String colorId, String sizeId) {
        boolean flag = true;
        boolean flag1 = false;
        int count;
        int num = 0;

        String id = UUIDUtil.getUUID();
        Format format = formatMapper.selectByCidAndSid(productId, colorId, sizeId);
        Product product = productMapper.selectByPrimaryKey(productId);
        String formatId = format.getId();
        String productName = product.getProductName();

        ShoppingCar s = new ShoppingCar();
        s.setUserId(userId);
        s.setNumber(number);
        s.setPrice(Integer.parseInt(price));
        s.setImageUrl(imageUrl);
        s.setId(id);
        s.setFormatId(formatId);
        s.setProductName(productName);

        ShoppingCar shop = shoppingCarMapper.selectByFidAndUid(formatId, userId);
        int store = formatMapper.getStoreById(formatId);

        //首先判断库存是否足够
        if (store > number) {
            //库存足够
            //再判断该商品是否已经存在购物车中,
            if (shop != null) {
                flag1 = true;
                num = shop.getNumber();
            }
        } else {
            //说明库存不够
            throw new NotEnoughException("该商品库存不足");
        }

        if (flag1) {
            //若存在则number加1,再更新购物车中的信息
            num += number;
            count = shoppingCarMapper.updateNumById(num, shop.getId());
        } else {
            count = shoppingCarMapper.addProduct(s);
        }
        if (count != 1) {
            flag = false;
        }

        return flag;
    }

    @Override
    public PaginationVO<Map<String, Object>> pageList(HashMap<String, Object> map) {

        //List<ShopData> sdList = new ArrayList<>();


        //取得total
        int total = shoppingCarMapper.getTotalByCondition(map);
        //取得list
        List<Map<String, Object>> scList = shoppingCarMapper.getShoppingCarListByCondition(map);

        //for (ShoppingCar sc : scList) {
        //    ShopData sd = new ShopData();
        //    sd.setProductName(sc.getProductName());
        //    sd.setPrice(sc.getPrice());
        //    sd.setImageUrl(sc.getImageUrl());
        //    sd.setNumber(sc.getNumber());
        //    sd.setId(UUIDUtil.getUUID());
        //
        //    Format format = formatMapper.selectByPrimaryKey(sc.getFormatId());
        //    String color = colorMapper.getColorById(format.getColorId());
        //    int size = sizeMapper.getSizeById(format.getSizeId());
        //
        //    sd.setSize(size);
        //    sd.setColor(color);
        //    sd.setStores(format.getStore());
        //    sdList.add(sd);
        //}


        //创建一个vo对象,将total和datalist封装到vo中
        PaginationVO<Map<String, Object>> vo = new PaginationVO<>();
        vo.setTotal(total);
        vo.setDataList(scList);

        return vo;
    }

    @Override
    public boolean deleteById(String id) {

        boolean flag = true;

        int count = shoppingCarMapper.deleteByPrimaryKey(id);

        if (count != 1) {
            flag = false;
        }

        return flag;
    }

    @Override
    public List<Map<String, Object>> carList(List<String> ids) {
        return shoppingCarMapper.carList(ids);
    }

    @Override
    public Address selectAddressByUid(String userId, int flag) {
        return addressMapper.selectAddressByUid(userId, flag);
    }

    @Transactional
    @Override
    public Map<String, Object> saveAddress(Address address) {

        boolean flag1 = false;
        boolean flag2 = false;
        String id = null;
        int postCode = 0;
        //注册时,新增的默认地址,是没有设置详细地址的,若可以找到则是初始的默认地址,则只需要更新信息即可,若为空,则说明不是初始地址,需要新增地址
        Address address1 = addressMapper.selectByAidAndPc(address.getId(), postCode);
        if (address1 != null) {

            String add = address.getAddress();
            String phone = address.getPhone();
            String fullName = address.getFullName();
            postCode = address.getPostCode();
            String email = address.getEmail();

            int count1 = addressMapper.updateById(address.getId(), add, phone, fullName, postCode, email);
            if (count1 == 1) {
                flag2 = true;
            }

        } else {
            //if (!address1.getAddress().equals(address.getAddress()) || !address1.getEmail().equals(address.getEmail()) || !address1.getPhone().equals(address.getPhone()) || !address1.getFullName().equals(address.getFullName()) || !address1.getPostCode().equals(address.getPostCode()))
            id = UUIDUtil.getUUID();
            String flag = "0";
            address.setId(id);
            address.setFlag(flag);

            int count = addressMapper.insertSelective(address);
            if (count == 1) {
                flag1 = true;
            }
        }
        Map<String, Object> map = new HashMap<>();
        if (flag1) {
            map.put("id", id);
            map.put("success", true);
        }
        if (flag2) {
            map.put("id", address.getId());
            map.put("success", true);
        }
        return map;
    }

    @Transactional
    @Override
    public Order deal(String psMethod, String userId, String addressId, String sid, String amountPrice) {

        boolean flag = true;

        //获取规格的id
        ShoppingCar shoppingCar = shoppingCarMapper.selectByPrimaryKey(sid);

        //获取该规格的信息
        Format format = formatMapper.selectByPrimaryKey(shoppingCar.getFormatId());
        Product product = productMapper.selectByPrimaryKey(format.getProductId());

        int sales = format.getSales();
        int store = format.getStore();

        //判断库存是否足够
        if (store < shoppingCar.getNumber()) {
            throw new NotEnoughException("商品库存不够");
        }

        int newSales = sales + shoppingCar.getNumber();
        int newStore = store - shoppingCar.getNumber();

        //销量增加库存减少
        int count = formatMapper.updateBySid(format.getId(), newSales, newStore);
        if (product.getPrice().equals(format.getPrice()) && product.getSales().equals(format.getSales())) {
            int count2 = productMapper.updateByPid(format.getProductId(), newSales);
            if (count2 != 1) {
                flag = false;
            }
        }

        if (count != 1) {
            flag = false;
        }

        Address address = addressMapper.selectByPrimaryKey(addressId);

        Order order = new Order();
        if (address.getPostCode() != 0) {
            //生成订单
            String id = UUIDUtil.getUUID();
            order.setId(id);
            order.setUserId(userId);
            order.setPsMethod(psMethod);
            order.setMoney(Integer.parseInt(amountPrice));
            order.setAddressId(addressId);
            order.setFormatId(format.getId());
            order.setNumber(shoppingCar.getNumber());
            order.setOrderTime(DateTimeUtil.getSysTime());
            //生成订单
            if (flag) {
                orderMapper.insert(order);
            }
        } else {
            throw new RuntimeException("请填写详细地址");
        }

        //删除购物车商品
        int count1 = shoppingCarMapper.deleteByPrimaryKey(sid);
        if (count1 != 1) {
            flag = false;
        }

        if (flag) {
            return order;
        }
        return null;
    }


}
